package com.github.tommas.admintpl.service;

import com.github.tommas.admintpl.cache.Cache;
import com.github.tommas.admintpl.cache.CacheManager;
import com.github.tommas.admintpl.config.CacheConfiguration;
import com.github.tommas.admintpl.security.permission.restriction.DeptIsolationRestriction;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class PermissionRestrictionService {

    @Autowired
    @Qualifier(CacheConfiguration.DEPT_ISOLATION_CACHE)
    private CacheManager<List<Integer>> entityIsolationCache;

    @Autowired
    private UserService userService;

    private static final Integer nonExistId = Integer.MIN_VALUE;

    public DeptIsolationRestriction getDeptIsolationRestriction(Integer userId) {
        Cache<List<Integer>> cache = entityIsolationCache.getCache(userId.toString());
        List<Integer> entityIds = cache.get();
        if (entityIds == null) {
            entityIds = userService.getUserEntities(userId);
            if (CollectionUtils.isEmpty(entityIds)) {
                entityIds = Collections.singletonList(nonExistId);
            }
            cache.put(entityIds);
        }

        return new DeptIsolationRestriction(entityIds);
    }
}
